package com.yami.shop.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.InventoryImportDTO;
import com.yami.shop.bean.dto.ProdInventoryDTO;
import com.yami.shop.bean.model.ProdInventory;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.dao.ProdInventoryMapper;
import com.yami.shop.service.ProdInventoryService;
import com.yami.shop.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 商品详细库存Service实现类
 */
@Service
@Slf4j
public class ProdInventoryServiceImpl extends ServiceImpl<ProdInventoryMapper, ProdInventory> implements ProdInventoryService {

    @Resource
    private MessageSource messageSource;
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<ProdInventoryDTO> pageProdInventory(Page<ProdInventoryDTO> page, Long prodId, Long shopId, Long categoryId, Integer status) {
        return baseMapper.pageProdInventory(page, prodId, shopId, categoryId, status);
    }

    @Override
    public ProdInventoryDTO getProdInventoryById(Long id) {
        if (id == null) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        ProdInventoryDTO prodInventoryDTO = baseMapper.getProdInventoryById(id);
//        if (prodInventoryDTO != null) {
//            // 获取密码并解密
//            ProdInventory prodInventory = getById(id);
//            if (prodInventory != null && StringUtils.hasText(prodInventory.getPassword())) {
//                // 这里假设密码是加密存储的，实际解密逻辑需要根据项目实际情况调整
//                // 由于PasswordEncoder是单向加密，这里只是示例，实际项目中可能需要使用其他加解密方式
//                prodInventoryDTO.setPassword(prodInventory.getDecryptedPassword());
//            }
//        }
        
        return prodInventoryDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProdInventory(ProdInventory prodInventory) {
//        validateProdInventory(prodInventory);
        
        // 设置默认状态为未售出
        if (prodInventory.getStatus() == null) {
            prodInventory.setStatus(1);
        }
        
//        // 如果有密码，进行加密
//        if (StringUtils.hasText(prodInventory.getDecryptedPassword())) {
//            prodInventory.setPassword(passwordEncoder.encode(prodInventory.getDecryptedPassword()));
//        }
        
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        prodInventory.setCreateTime(now);
        prodInventory.setUpdateTime(now);
        
        boolean result = save(prodInventory);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.add.failed", null, LocaleContextHolder.getLocale()));
        }
        
        // 更新商品总库存
        updateProductTotalStocks(prodInventory.getProdId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAddProdInventory(InventoryImportDTO inventoryImportDTO) {
        if (inventoryImportDTO == null || inventoryImportDTO.getAccountPasswords() == null || inventoryImportDTO.getAccountPasswords().isEmpty()) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.list.empty", null, LocaleContextHolder.getLocale()));
        }
        Long prodId = inventoryImportDTO.getProductId();
        LocalDateTime now = LocalDateTime.now();
        if (inventoryImportDTO.getCheckDuplicate() == null) {
            List<ProdInventory> prodInventoryList = new ArrayList<>();
            for (String str : inventoryImportDTO.getAccountPasswords()) {
                List<String> strs = Arrays.asList(str.split(" "));
                ProdInventory prodInventory = new ProdInventory();
                // 设置默认状态为未售出
                prodInventory.setStatus(1);
                // 设置创建时间和更新时间
                prodInventory.setCreateTime(now);
                prodInventory.setUpdateTime(now);
                prodInventory.setProdId(inventoryImportDTO.getProductId());
                prodInventory.setShopId(inventoryImportDTO.getShopId());
                prodInventory.setPassword(strs.get(1));
                prodInventory.setCardNumber(strs.get(0));
                prodInventoryList.add(prodInventory);
            }
            boolean result = saveBatch(prodInventoryList);
            if (!result) {
                throw new YamiShopBindException(messageSource.getMessage("prod.inventory.batch.add.failed", null, LocaleContextHolder.getLocale()));
            }
        }else {
            Set<ProdInventory> prodInventoryList = new HashSet<>();
            for (String str : inventoryImportDTO.getAccountPasswords()) {
                List<String> strs = Arrays.asList(str.split(" "));
//            validateProdInventory(prodInventory);
                ProdInventory prodInventory = new ProdInventory();
                // 设置默认状态为未售出
                prodInventory.setStatus(1);
                // 设置创建时间和更新时间
                prodInventory.setCreateTime(now);
                prodInventory.setUpdateTime(now);
                prodInventory.setProdId(inventoryImportDTO.getProductId());
                prodInventory.setShopId(inventoryImportDTO.getShopId());
                prodInventory.setPassword(strs.get(1));
                prodInventory.setCardNumber(strs.get(0));
                prodInventoryList.add(prodInventory);
            }
            boolean result = saveBatch(prodInventoryList);
            if (!result) {
                throw new YamiShopBindException(messageSource.getMessage("prod.inventory.batch.add.failed", null, LocaleContextHolder.getLocale()));
            }
        }
        // 更新商品总库存
        if (prodId != null) {
            updateProductTotalStocks(prodId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProdInventory(ProdInventory prodInventory) {
        if (prodInventory.getId() == null) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        
        ProdInventory existInventory = getById(prodInventory.getId());
        if (existInventory == null) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.not.exist", null, LocaleContextHolder.getLocale()));
        }
        
        // 记录原商品ID，用于后续更新总库存
        Long oldProdId = existInventory.getProdId();
        
        // 如果有密码，进行加密
        if (StringUtils.hasText(prodInventory.getDecryptedPassword())) {
            prodInventory.setPassword(passwordEncoder.encode(prodInventory.getDecryptedPassword()));
        }
        
        // 设置更新时间
        prodInventory.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(prodInventory);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.update.failed", null, LocaleContextHolder.getLocale()));
        }
        
        // 如果商品ID发生变化，需要更新两个商品的总库存
        if (prodInventory.getProdId() != null && !prodInventory.getProdId().equals(oldProdId)) {
            updateProductTotalStocks(oldProdId);
            updateProductTotalStocks(prodInventory.getProdId());
        } else if (oldProdId != null) {
            // 更新商品总库存
            updateProductTotalStocks(oldProdId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProdInventory(Long id) {
        if (id == null) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.id.not.null", null, LocaleContextHolder.getLocale()));
        }
        
        ProdInventory prodInventory = getById(id);
        if (prodInventory == null) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.not.exist", null, LocaleContextHolder.getLocale()));
        }
        
        // 记录商品ID，用于后续更新总库存
        Long prodId = prodInventory.getProdId();
        
        boolean result = removeById(id);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.delete.failed", null, LocaleContextHolder.getLocale()));
        }
        
        // 更新商品总库存
        if (prodId != null) {
            updateProductTotalStocks(prodId);
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteProdInventory(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.ids.empty", null, LocaleContextHolder.getLocale()));
        }
        
        // 获取所有库存记录，用于后续更新总库存
        List<ProdInventory> prodInventoryList = listByIds(ids);
        if (prodInventoryList.isEmpty()) {
            return;
        }
        
        boolean result = removeByIds(ids);
        if (!result) {
            throw new YamiShopBindException(messageSource.getMessage("prod.inventory.batch.delete.failed", null, LocaleContextHolder.getLocale()));
        }
        
        // 更新所有相关商品的总库存
        List<Long> prodIds = new ArrayList<>();
        for (ProdInventory prodInventory : prodInventoryList) {
            if (prodInventory.getProdId() != null && !prodIds.contains(prodInventory.getProdId())) {
                prodIds.add(prodInventory.getProdId());
            }
        }
        
        for (Long prodId : prodIds) {
            updateProductTotalStocks(prodId);
        }
    }


    /**
     * 更新商品总库存
     * @param prodId 商品ID
     */
    private void updateProductTotalStocks(Long prodId) {
        if (prodId == null) {
            log.warn("更新商品总库存失败：商品ID为空");
            return;
        }
        try {
            // 获取商品信息
            Product product = productService.getById(prodId);
            if (product == null) {
                log.warn("更新商品总库存失败：商品不存在，prodId={}", prodId);
                return;
            }

            // 统计未售出和锁定状态的库存数量
            int availableStocks = baseMapper.countByProdIdAndStatus(prodId, 1); // 未售出
            int lockedStocks = baseMapper.countByProdIdAndStatus(prodId, 2);    // 锁定状态

            // 总库存 = 未售出 + 锁定状态
            int totalStocks = availableStocks + lockedStocks;

            // 更新商品总库存
            product.setTotalStocks(totalStocks);

            // 保存更新
            boolean result = productService.updateById(product);
            if (!result) {
                log.error("更新商品总库存失败：保存失败，prodId={}", prodId);
            } else {
                log.info("更新商品总库存成功：prodId={}，totalStocks={}", prodId, totalStocks);
            }
        } catch (Exception e) {
            log.error("更新商品总库存异常：prodId={}", prodId, e);
        }
    }

} 